package assists.resource
{
	import assists.log.Log;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.utils.setTimeout;
	
	public class ImageResource extends Sprite
	{
		private var _loader:ResourceLoader;
		private var _path:String;
		private var _callBack:Function;
		
		public function ImageResource(loader:ResourceLoader,url:String,callBack:Function = null)
		{
			_loader = loader;
			_path = url;
			_callBack = callBack;
			
			if(url == "")
			{
				this.addChild(_loader.uiManager.generateBmp(_loader.uiManager.noPic,true));
				if(_callBack != null)
				{
					setTimeout(function():void
					{
						_callBack();
					}
						,200);
				}
				return;
			}
			
			getImg();
		}
		
		private function getImg():void
		{
			if(_loader && _path){
				if(_loader.getImage(_path) != null){
					if(_callBack != null)
					{
					setTimeout(function():void
					{
						addPic();
						_callBack();
					}
						,200);
					}else
					{
						addPic();
					}
				}else{
					_loader.load([_loader.getLoadData(_path, "")], progress, loadComplete);
				}
			}
		}
		
		private function progress(par1:String,par2:Number,par3:Number):void
		{
//			Log.trace("图片在拉取" + par1 + " "+ par2 + " " + par3);
		}
		
		private function loadComplete():void
		{
			clearThis();
			addPic();
			if(_callBack is Function){
				_callBack();
			}
		}
		
		private function addPic():void
		{
			var img:Bitmap = _loader.getImage(_path);
			this.addChildAt(img,0);		
		}
		
		private function clearThis() : void
		{
		  this.removeChildren();
		}
		
		public function dispose():void
		{
			this.clearThis();
		}
		
		public function get imageData():BitmapData
		{
			return this._loader.getImage(_path).bitmapData;
		}
	}
}